package DAOImpl;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.oocl.util.DBUtil;

import pojo.User;
import DAO.UserDAO;

public class UserDAOImpl implements UserDAO{

	@Override
	public int insertUser(User user) {
		String sql = "insert into usertable(id,uname,sal,birth,sex) values(seq02.nextval,?,?,?,?)";
		PreparedStatement pst = null;
		Connection con =null;
		int index = 0;
		try {
			con = DBUtil.getConnection();
			pst = con.prepareStatement(sql);
			pst.setString(1, user.getUname());
			pst.setDouble(2, user.getSal());
			pst.setDate(3, new java.sql.Date(user.getBirth().getTime()));
			pst.setBoolean(4, user.isSex());
			index = pst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		DBUtil.release(con, pst, null);
		return index;
	}

	@Override
	public List<User> findAll() {
		 String sql ="select id,uname,sal,birth,sex from usertable";
		 List<User> list = new ArrayList<User>();
		 Connection con = null;
		 PreparedStatement pst  = null;
		 ResultSet rs = null;
		 try {
			 
			 con = DBUtil.getConnection();
			 pst = con.prepareStatement(sql);
			 rs = pst.executeQuery();
			 while(rs.next()){
				 User user = new User();
				 user.setId(rs.getInt(1));
				 user.setUname(rs.getString(2));
				 user.setSal(rs.getDouble(3));
				 user.setBirth(new Date(rs.getDate(4).getTime()));
				 user.setSex(rs.getBoolean(5));
				 list.add(user);
			 }
		} catch (SQLException e) {
			e.printStackTrace();
		}
		DBUtil.release(con, pst, rs);
		return list;
	}
	
}
